﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using LWrap.IndexSource;
using LWrap.FileParsers;
namespace LWrap.Index
{
    internal class IndexData
    {
        public Lucene.Net.Documents.Document PrepareField(Lucene.Net.Documents.Document document,IndexDataSource source)
        {
            string[] delim = new string[1];
            delim[0] = string.Empty;
            delim[0] = "\t";
            if (string.IsNullOrEmpty(source.DocFields)==false)
            {

                string[] fields = source.DocFields.Split(delim, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < fields.Length - 1; i = i + 2)
                {
                    Lucene.Net.Documents.Field fldContent = new Lucene.Net.Documents.Field(fields[i], fields[i + 1], Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES);
                    document.Add(fldContent);
                }
            }
            if (source.DocName != null)
            {
                Lucene.Net.Documents.Field fldDocName = new Lucene.Net.Documents.Field("DocName", source.DocName, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES);
                document.Add(fldDocName);
            }

            if (source.ModifiedDate != null)
            {
                Lucene.Net.Documents.Field fldDocDate = new Lucene.Net.Documents.Field("ModifiedDate", source.ModifiedDate, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES);
                document.Add(fldDocDate);
            }

            if (source.DocContent != null)
            {
                StreamReader reader = new StreamReader(source.DocName, System.Text.Encoding.Default);
                FileParserBase parser = FileParserFactory.GetFileParser(source.DocName);
                string text = parser.ExtractText(source.DocName);
                Lucene.Net.Documents.Field fldDocDate = new Lucene.Net.Documents.Field("DocContent", text, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES);
                document.Add(fldDocDate);
                //document.Add(new Lucene.Net.Documents.Field("DocContent", source.DocContent.ReadToEnd(), Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED, Lucene.Net.Documents.Field.TermVector.YES));
                //document.Add(new Lucene.Net.Documents.Field("DocContent", new System.IO.StreamReader(source.DocName, System.Text.Encoding.Default)));

            }
            return document;

        }
    }
}
